package com.listeningframework.boot.codegen.context;

import com.listeningframework.boot.codegen.database.MetaLoader;
import com.listeningframework.boot.codegen.database.MetaLoaderFactory;
import com.listeningframework.boot.codegen.exception.CodeGenException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lixining on 2017/8/8.
 */
public class ModuleContext {
    /**
     * 是否有效
     */
    private boolean enabled;
    /**
     * ORM框架
     */
    private String orm;
    /**
     * 是否从数据库读取
     */
    private boolean readFromDB;
    /**
     * 是否生成文件
     */
    private boolean generate;
    /**
     * Entity列表
     */
    private List<EntityContext> entityContextList;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getOrm() {
        return orm;
    }

    public void setOrm(String orm) {
        this.orm = orm;
    }

    public boolean isReadFromDB() {
        return readFromDB;
    }

    public void setReadFromDB(boolean readFromDB) {
        this.readFromDB = readFromDB;
    }

    public boolean isGenerate() {
        return generate;
    }

    public void setGenerate(boolean generate) {
        this.generate = generate;
    }

    public List<EntityContext> getEntityContextList() {
        return entityContextList;
    }

    public void setEntityContextList(List<EntityContext> entityContextList) {
        this.entityContextList = entityContextList;
    }

    public void addEntity(EntityContext entityContext) {
        if (this.entityContextList == null) {
            this.entityContextList = new ArrayList<EntityContext>();
        }
        this.entityContextList.add(entityContext);
    }

    public void afterProperties() throws CodeGenException {
        if (this.entityContextList == null || this.entityContextList.isEmpty()) {
            return;
        }
        MetaLoader metaLoader = MetaLoaderFactory.getLoader();
        for (EntityContext entityContext : this.entityContextList) {
            entityContext.setTableMetaDataList(metaLoader.getMetaData(entityContext.getTable()));
        }
    }

    /**
     * 是否存在要生成代码的Entity列表
     *
     * @return boolean
     */
    public boolean existsEntities() {
        return entityContextList != null && !entityContextList.isEmpty();
    }

    public boolean isOrmMyBatis() {
        return StringUtils.equalsIgnoreCase("mybatis", this.orm);
    }

    public boolean isOrmJpa() {
        return StringUtils.equalsIgnoreCase("jpa", this.orm);
    }

}
